package com.itheima.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * 安全配置信息
 *
 * @EnableWebSecurity 开启security配置，进入注解源代码中 有注释说明如何使用
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)  //开启方法级别权限校验， prePostEnabled调用方法之前校验权限
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    /**
     * 1.配置Bcrypt加密对象，用于对用户密码进行加密
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    /*
        2.在内存中定义一些用户信息 UserDetailsService（用户名，密码（密码需要进行加密），角色权限）
        security框架中角色跟权限 写法一样  要求角色ROLE_
     */
    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("jack").password(passwordEncoder().encode("jack")).authorities("p1", "p", "ROLE_ADMIN").build());
        manager.createUser(User.withUsername("rose").password(passwordEncoder().encode("rose")).authorities("p2", "p", "ROLE_USER").build());
        return manager;
    }

    /**
     * 3.配置资源的访问规则（资源有什么权限才能访问资源）
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin()   //开启表单认证
                .and()
                //本质上 拦截到请求后 判断当前用户是否有某个权限-过滤器
                .authorizeRequests()
                .antMatchers("/hello").access("hasAuthority('p') and hasRole('ROLE_ADMIN')") // /hello接口地址 必须有p权限才能访问
                .antMatchers("/r/r1").access("hasAuthority('p1')")
                .antMatchers("/r/r2").access("hasAuthority('p2')")
                .anyRequest().authenticated();  //剩余的其他请求 认证后 方可访问
    }
}
